<template>
  <div id="Destroy">
    <a-row :gutter="16">
      <a-col :span="7">
        <a-card title="单纤轮询" :bordered="false" class="query-card">
          <template #extra>
            <a-button type="link" @click="handleSingleQuery">查询</a-button>
          </template>
          <a-spin :spinning="loading.single">
            <div v-if="singleQueryResult">
              <a-table
                :columns="columns"
                :data-source="singleTableData"
                :pagination="{
                  pageSize: 5,
                  total: singleTableData.length,
                  hideOnSinglePage: true,
                }"
                :scroll="{ y: 200 }"
                size="small"
              />
            </div>
            <a-empty v-else description="暂无数据" />
          </a-spin>
          </a-card>
        <a-card
          v-if="singleQueryResult"
          :bordered="false"
          class="query-card"
          style="margin-top: 16px"
        >
          <template #title>单纤轮询统计</template>
          <a-spin :spinning="loading.single">
            <div
              ref="singlePieRef"
              style="height: 300px; width: 100%; position: relative"
            >
              <div
                v-if="!singlePieChart"
                style="
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  transform: translate(-50%, -50%);
                  color: #999;
                "
              >
                加载中...
              </div>
            </div>
          </a-spin>
          </a-card>
      </a-col>
      <a-col :span="7">
        <a-card title="双纤轮询" :bordered="false" class="query-card">
          <template #extra>
            <a-button type="link" @click="handleDoubleQuery">查询</a-button>
          </template>
          <a-spin :spinning="loading.double">
            <div v-if="doubleQueryResult">
              <a-table
                :columns="columns"
                :data-source="doubleTableData"
                :pagination="{
                  pageSize: 5,
                  total: doubleTableData.length,
                  hideOnSinglePage: true,
                }"
                :scroll="{ y: 200 }"
                size="small"
              />
            </div>
            <a-empty v-else description="暂无数据" />
          </a-spin>
          </a-card>
        <a-card
          v-if="doubleQueryResult"
          :bordered="false"
          class="query-card"
          style="margin-top: 16px"
        >
          <template #title>双纤轮询统计</template>
          <a-spin :spinning="loading.double">
            <div
              ref="doublePieRef"
              style="height: 300px; width: 100%; position: relative"
            >
              <div
                v-if="!doublePieChart"
                style="
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  transform: translate(-50%, -50%);
                  color: #999;
                "
              >
                加载中...
              </div>
            </div>
          </a-spin>
          </a-card>
      </a-col>
      <a-col :span="10">
        <a-card title="组合轮询" :bordered="false" class="query-card">
          <template #extra>
            <a-space>
              <a-select
                v-model:value="destroyParams.nodeNames"
                mode="multiple"
                placeholder="损坏节点"
                :options="nodeStore.nodeNameListSelect"
                style="width: 200px"
                size="small"
              />
              <a-select
                v-model:value="destroyParams.fiberNames"
                mode="multiple"
                placeholder="损坏链路"
                :options="fiberStore.fiberNameListSelect"
                style="width: 200px"
                size="small"
              />
              <a-button type="link" @click="handleDestroyOk">查询</a-button>
            </a-space>
          </template>
          <a-spin :spinning="loading.destroy">
            <div v-if="destroyResult">
              <a-table
                :columns="destroyColumns"
                :data-source="destroyTableData"
                :pagination="{
                  pageSize: 5,
                  total: destroyTableData.length,
                  hideOnSinglePage: true
                }"
                :scroll="{ y: 200 }"
                size="small"
              />
            </div>
            <a-empty v-else description="暂无数据" />
          </a-spin>
        </a-card>
        <a-card
          v-if="destroyResult"
          :bordered="false"
          class="query-card"
          style="margin-top: 16px"
        >
          <template #title>组合轮询统计</template>
          <a-spin :spinning="loading.destroy">
            <div
              ref="destroyPieRef"
              style="height: 300px; width: 100%; position: relative"
            >
              <div
                v-if="!destroyPieChart"
                style="
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  transform: translate(-50%, -50%);
                  color: #999;
                "
              >
                加载中...
              </div>
            </div>
          </a-spin>
          </a-card>
      </a-col>
    </a-row>

    <!-- 详情模态框 -->
    <a-modal
      v-model:visible="detailModalVisible"
      title="业务详情"
      width="1000px"
      @cancel="() => (detailModalVisible = false)"
      :footer="null"
    >
      <template v-if="currentDetail">
        <a-table
          :columns="detailTable1Columns"
          :data-source="currentDetail.table1Data"
          :pagination="false"
          style="margin-bottom: 16px"
        />
        <a-divider />
        <a-table
          :columns="detailTable2Columns"
          :data-source="currentDetail.table2Data"
          :pagination="false"
        />
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, h, nextTick, watch } from "vue";
import useNode from "../store/node";
import useFiber from "../store/fiber.js";
import useProject from "../store/project.js";
import { storeToRefs } from "pinia";
import { Service } from "../requests/services/Service";
import { message, Tag } from "ant-design-vue";
import * as echarts from "echarts";
import useDemand from "../store/demand.js";

const nodeStore = useNode();
const fiberStore = useFiber();
const projectStore = useProject();
const { currentProject } = storeToRefs(projectStore);
const demandStore = useDemand();

// 表格列定义
const columns = [
  {
    title: "链路名称",
    dataIndex: "linkName",
    key: "linkName",
    width: "60%",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: "40%",
    sorter: (a, b) => a.status - b.status,
    customRender: ({ text: status }) => {
      let config = {
        1: { text: "已恢复", color: "green" },
        2: { text: "不受影响", color: "blue" },
      }[status] || { text: "未恢复", color: "red" };

      return h(Tag, { color: config.color }, () => config.text);
    },
  },
];

const destroyParams = ref({
  nodeNames: [],
  fiberNames: [],
});

// 添加加载状态
const loading = ref({
  single: false,
  double: false,
  destroy: false
});

// 查询结果状态
const singleQueryResult = ref(null);
const doubleQueryResult = ref(null);
const singleTableData = ref([]);
const doubleTableData = ref([]);
const singlePieRef = ref(null);
const doublePieRef = ref(null);
let singlePieChart = null;
let doublePieChart = null;

// 组合轮询表格列定义
const destroyColumns = [
  {
    title: "业务名称",
    dataIndex: "demandName",
    key: "demandName",
    width: "50%",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: "30%",
    sorter: (a, b) => a.statusCode - b.statusCode,
    customRender: ({ text: status }) => {
      let config = {
        0: { text: "未恢复", color: "red" },
        1: { text: "已恢复", color: "green" },
        2: { text: "不受影响", color: "blue" },
      }[status.code] || { text: "未知", color: "default" };

      return h(Tag, { color: config.color }, () => config.text);
    },
  },
  {
    title: "详情",
    key: "action",
    width: "20%",
    customRender: ({ record }) => {
      return h(
        "a",
        {
          onClick: () => showDetail(record),
        },
        "查看详情"
      );
    },
  },
];

// 组合轮询相关状态
const destroyResult = ref(null);
const destroyTableData = ref([]);
const destroyPieRef = ref(null);
let destroyPieChart = null;

// 详情模态框相关
const detailModalVisible = ref(false);
const currentDetail = ref(null);

// 详情表格1列定义
const detailTable1Columns = [
  {
    title: "业务名称",
    dataIndex: "demandName",
    key: "demandName",
  },
  {
    title: "恢复状态",
    dataIndex: "status",
    key: "status",
    customRender: ({ text: status }) => {
      let config = {
        0: { text: "未恢复", color: "red" },
        1: { text: "已恢复", color: "green" },
        2: { text: "不受影响", color: "blue" },
      }[status.code] || { text: "未知", color: "default" };

      return h(Tag, { color: config.color }, () => config.text);
    },
  },
  {
    title: "保护方式",
    dataIndex: "protectType",
    key: "protectType",
  },
];

// 详情表格2列定义
const detailTable2Columns = [
  {
    title: "网络名称",
    dataIndex: "networkName",
    key: "networkName",
    width: "15%",
  },
  {
    title: "原工作路由",
    dataIndex: "originalWorkRoute",
    key: "originalWorkRoute",
    width: "20%",
  },
  {
    title: "原保护路由",
    dataIndex: "originalProtectRoute",
    key: "originalProtectRoute",
    width: "20%",
  },
  {
    title: "现工作路由",
    dataIndex: "currentWorkRoute",
    key: "currentWorkRoute",
    width: "20%",
  },
  {
    title: "现保护路由",
    dataIndex: "currentProtectRoute",
    key: "currentProtectRoute",
    width: "25%",
  },
];

// 显示详情
const showDetail = async (record) => {
  try {
    // 获取业务详情
    const demandDetail = await demandStore.getSingleDemand(currentProject.value.name, record.demandName);
    
    // 获取状态
    const isUnaffected = record.status.code === 2; // 不受影响
    console.log("demandDetail", demandDetail)
    // 获取原始路由信息
    const net1OriginalWorkRoute = demandDetail?.routeFibers?.length ? demandDetail.routeFibers : '无';
    const net1OriginalProtectRoute = demandDetail?.protectRouteFibers?.length ? demandDetail.protectRouteFibers : '无';
    const net2OriginalWorkRoute = demandDetail?.doubleRouteFibers?.length ? demandDetail.doubleRouteFibers : '无';
    const net2OriginalProtectRoute = demandDetail?.doubleProtectRouteFibers?.length ? demandDetail.doubleProtectRouteFibers : '无';
    
    // 获取当前路由信息（从轮询结果中获取）
    const survivalData = demandStore.survivalResult[record.demandName] || {};
    const net1CurrentWorkRoute = isUnaffected ? net1OriginalWorkRoute : 
                               (survivalData.route?.linkList?.length ? getRouteString(survivalData.route.linkList) : '无');
    const net1CurrentProtectRoute = isUnaffected ? net1OriginalProtectRoute : 
                                  (survivalData.protectRoute?.linkList?.length ? getRouteString(survivalData.protectRoute.linkList) : '无');
    const net2CurrentWorkRoute = isUnaffected ? net2OriginalWorkRoute : 
                               (survivalData.doubleRoute?.linkList?.length ? getRouteString(survivalData.doubleRoute.linkList) : '无');
    const net2CurrentProtectRoute = isUnaffected ? net2OriginalProtectRoute : 
                                  (survivalData.doubleProtectRoute?.linkList?.length ? getRouteString(survivalData.doubleProtectRoute.linkList) : '无');

    currentDetail.value = {
      table1Data: [
        {
          demandName: record.demandName,
          status: record.status,
          protectType: demandDetail?.protect || '无', // 从业务详情中获取保护方式
        },
      ],
      table2Data: [
        {
          key: "1",
          networkName: "网络1",
          originalWorkRoute: net1OriginalWorkRoute,
          originalProtectRoute: net1OriginalProtectRoute,
          currentWorkRoute: net1CurrentWorkRoute,
          currentProtectRoute: net1CurrentProtectRoute,
        },
        {
          key: "2",
          networkName: "网络2",
          originalWorkRoute: net2OriginalWorkRoute,
          originalProtectRoute: net2OriginalProtectRoute,
          currentWorkRoute: net2CurrentWorkRoute,
          currentProtectRoute: net2CurrentProtectRoute,
        },
      ],
    };
    detailModalVisible.value = true;
  } catch (error) {
    console.error("获取详情失败：", error);
    message.error("获取详情失败");
  }
};

// 获取路由字符串
const getRouteString = (linkList) => {
  if (!linkList || linkList.length === 0) return "无路由";

  // 提取路由路径
  const path = linkList.map((link) => {
    if (link.nodeHeadName && link.nodeTailName) {
      return `${link.nodeHeadName}-${link.nodeTailName}`;
    }
    return link.name;
  });

  // 去重并连接
  return [...new Set(path)].join(" -> ");
};

// 处理数据并更新图表
const processQueryData = (data, type) => {
  console.log(`处理${type}数据:`, data);
  const tableData = [];
  const stats = {
    未恢复: 0,
    已恢复: 0,
    不受影响: 0,
  };

  // 遍历所有数据项，统计状态
  Object.entries(data).forEach(([key, value]) => {
    if (!["未恢复", "已恢复", "不受影响"].includes(key)) {
      if (value === 1) {
        stats["已恢复"]++;
      } else if (value === 2) {
        stats["不受影响"]++;
      } else {
        stats["未恢复"]++;
      }
    }
  });

  console.log(`${type}统计数据:`, stats);

  // 处理链路数据
  Object.entries(data).forEach(([key, value]) => {
    if (!["未恢复", "已恢复", "不受影响"].includes(key)) {
      const linkName =
        type === "double"
          ? key
              .replace(/[\[\]]/g, "")
              .split(", ")
              .join(" - ")
          : key;
      tableData.push({
        key,
        linkName,
        status: value,
      });
    }
  });

  // 更新表格数据
  if (type === "single") {
    singleTableData.value = tableData;
    nextTick(() => {
      console.log("更新单纤饼图");
      if (singlePieChart) {
        updatePieChart(singlePieChart, stats, "单纤轮询统计");
      } else {
        console.warn("单纤饼图实例不存在");
        singlePieChart = echarts.init(singlePieRef.value);
        updatePieChart(singlePieChart, stats, "单纤轮询统计");
      }
    });
  } else {
    doubleTableData.value = tableData;
    nextTick(() => {
      console.log("更新双纤饼图");
      if (doublePieChart) {
        updatePieChart(doublePieChart, stats, "双纤轮询统计");
      } else {
        console.warn("双纤饼图实例不存在");
        doublePieChart = echarts.init(doublePieRef.value);
        updatePieChart(doublePieChart, stats, "双纤轮询统计");
      }
    });
  }
};

// 更新饼图
const updatePieChart = (chart, stats, title) => {
  console.log("更新饼图:", title, stats);
  if (!chart) {
    console.warn("图表实例不存在");
    return;
  }

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      orient: "horizontal",
      bottom: 30,
      left: "center",
      itemGap: 20, // 图例项之间的间距
      data: Object.keys(stats),
    },
    grid: {
      top: 0,
      bottom: 0,
    },
    series: [
      {
        name: "轮询结果",
        type: "pie",
        radius: ["35%", "60%"], // 减小饼图大小
        center: ["50%", "40%"], // 将中心点更靠上
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}: {c}",
          position: "outside", // 将标签放在外部
          alignTo: "none", // 不对齐到边缘
          edgeDistance: "10%", // 标签与图形的距离
        },
        labelLine: {
          length: 10, // 第一段线长
          length2: 10, // 第二段线长
          smooth: true, // 平滑的线条
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "16",
            fontWeight: "bold",
          },
        },
        data: Object.entries(stats).map(([name, value]) => ({
          name,
          value,
          itemStyle: {
            color:
              name === "未恢复"
                ? "#ff4d4f"
                : name === "已恢复"
                ? "#52c41a"
                : name === "不受影响"
                ? "#1890ff"
                : "#d9d9d9",
          },
        })),
      },
    ],
  };

  try {
    chart.setOption(option);
    console.log("饼图更新成功");
  } catch (error) {
    console.error("饼图更新失败:", error);
  }
};

// 单纤轮询处理函数
const handleSingleQuery = async () => {
  loading.value.single = true;
  try {
    const res = await Service.singleQueryUsingGet(currentProject.value.name);
    console.log("单纤轮询结果:", res);
    if (res && res.data) {
      singleQueryResult.value = res.data;
      processQueryData(res.data, "single");
      message.success("单纤轮询完成");
    } else {
      message.error("单纤轮询数据格式错误");
    }
  } catch (error) {
    console.error("单纤轮询错误:", error);
    message.error("单纤轮询失败");
  } finally {
    loading.value.single = false;
  }
};

// 双纤轮询处理函数
const handleDoubleQuery = async () => {
  loading.value.double = true;
  try {
    const res = await Service.doubleQueryUsingGet(currentProject.value.name);
    console.log("双纤轮询结果:", res);
    if (res && res.data) {
      doubleQueryResult.value = res.data;
      processQueryData(res.data, "double");
      message.success("双纤轮询完成");
    } else {
      message.error("双纤轮询数据格式错误");
    }
  } catch (error) {
    console.error("双纤轮询错误:", error);
    message.error("双纤轮询失败");
  } finally {
    loading.value.double = false;
  }
};

// 处理组合轮询数据
const processDestroyData = (data) => {
  console.log("处理组合轮询数据:", data);
  const tableData = [];
  const stats = {
    未恢复: 0,
    已恢复: 0,
    不受影响: 0,
  };

  // 处理数据
  data.forEach((item) => {
    // 这里需要根据实际数据结构判断业务状态
    let status = determineStatus(item);

    // 更新统计
    stats[status.text]++;

    // 添加到表格数据
    tableData.push({
      key: item.demandName,
      demandName: item.demandName,
      status: status,
    });
  });

  console.log("组合轮询统计:", stats);
  destroyTableData.value = tableData;

  // 更新饼图
  nextTick(() => {
    if (destroyPieChart) {
      updatePieChart(destroyPieChart, stats, "组合轮询统计");
    } else if (destroyPieRef.value) {
      destroyPieChart = echarts.init(destroyPieRef.value);
      updatePieChart(destroyPieChart, stats, "组合轮询统计");
    }
  });
};

// 判断业务状态
const determineStatus = (item) => {
  // 这里需要根据实际数据结构判断业务状态
  // 示例逻辑，需要根据实际数据调整
  if (item.route && item.protectRoute) {
    if (!item.route.linkList.length && !item.protectRoute.linkList.length) {
      return { code: 0, text: "未恢复" };
    } else if (
      item.route.linkList.length &&
      item.protectRoute.linkList.length
    ) {
      return { code: 1, text: "已恢复" };
    } 
  }
  return { code: 2, text: "不受影响" };
};

// 组合轮询处理函数
const handleDestroyOk = async () => {
  loading.value.destroy = true;
  try {
    const res = await Service.survivalUsingPost(
      currentProject.value.name,
      destroyParams.value.fiberNames,
      destroyParams.value.nodeNames
    );
    console.log("组合轮询结果:", res);
    if (res && res.data) {
      // 存储轮询结果
      demandStore.setSurvivalResult(res.data);
      destroyResult.value = res.data;
      processDestroyData(res.data);
      message.success("组合轮询完成");
    } else {
      message.error("组合轮询数据格式错误");
    }
  } catch (error) {
    console.error("组合轮询错误:", error);
    message.error("组合轮询失败");
  } finally {
    loading.value.destroy = false;
  }
};

// 初始化图表和默认选择
onMounted(() => {
  console.log("组件挂载");
  nextTick(() => {
    console.log("DOM更新完成");
    if (singlePieRef.value) {
      console.log("初始化单纤饼图");
      singlePieChart = echarts.init(singlePieRef.value);
      window.addEventListener("resize", () => singlePieChart.resize());
    }
    if (doublePieRef.value) {
      console.log("初始化双纤饼图");
      doublePieChart = echarts.init(doublePieRef.value);
      window.addEventListener("resize", () => doublePieChart.resize());
    }
    if (destroyPieRef.value) {
      console.log("初始化组合轮询饼图");
      destroyPieChart = echarts.init(destroyPieRef.value);
      window.addEventListener("resize", () => destroyPieChart.resize());
    }

    // 自动调用单纤和双纤轮询
    if (currentProject.value?.name) {
      handleSingleQuery();
      handleDoubleQuery();
      
      // 设置默认选择第一条链路和第一个节点
      if (fiberStore.fiberNameListSelect.length > 0) {
        destroyParams.value.fiberNames = [fiberStore.fiberNameListSelect[0].value];
      }
      if (nodeStore.nodeNameListSelect.length > 0) {
        destroyParams.value.nodeNames = [nodeStore.nodeNameListSelect[0].value];
      }
      // 自动执行组合轮询
      handleDestroyOk();
    }
  });
});

// 监听项目变化，当项目改变时自动调用轮询
watch(
  () => currentProject.value?.name,
  (newProjectName) => {
    if (newProjectName) {
      handleSingleQuery();
      handleDoubleQuery();
    }
  }
);
</script>

<style scoped>
.query-card {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.query-card :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 16px;
}

.query-card :deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-table-wrapper) {
  border-radius: 4px;
}

:deep(.ant-table-pagination) {
  margin: 8px 0;
}
</style>
